<?php
include_once('/var/www/html/new/com.inc.php');
include_once('/var/www/html/new/d/module/wxh/class/Terminal_Check_Socket.class.php');
// 身份验证 只有供应商、商户、管理员可以进行验证
if(!isset($_SESSION['sid'])) exit('{"status":"fail","msg":"请先登录后再操作","code":0}');
if(!in_array($_SESSION['sdtype'], array(0,2,3,6,9))) exit('{"status":"fail","msg":"身份不合法"}');
$ac = $GLOBALS['_ac'];
$pw = $GLOBALS['_pw'];
$s  = new SoapClient(null,array("location" => "http://localhost/open/openService/pft_insideMX.php","uri" => "www.16u.com?ac_16u=$ac|pw_16u=$pw|auth_16u=true"));
// 接收数据
$salerid = $_REQUEST['salerid'] + 0;// 商户ID
$voucher = $_REQUEST['voucher'];// 凭证码
/**
 * 验证部分
 * @param salerid  产品编号
 * @param voucher   证码，电话号码两者任意一种
 */
if($_REQUEST['data']=="1"){
    // 接收数据
    $id        = $_REQUEST['id'] + 0;// 产品ID
    $voucher   = $_REQUEST['voucher'] ;// 凭证码或手机号
    $terminal  = $_REQUEST['terminal']+ 0;//终端号
    $salerid   = $_REQUEST['salerid'] + 0;// 产品编码
    $verify    = new PsVerfiy($s, $salerid);
    $memberSID = $_SESSION['sid'];
    $memberID  = $_SESSION['memberID'];

    $sql = "select terminal,terminal_type,salerid from uu_land where id=$id limit 1";
    $GLOBALS['le']->query($sql);
    if(!$GLOBALS['le']->fetch_assoc()) exit('{"status":"fail","msg":"未找到景区"}');
    $terminal_type = $GLOBALS['le']->f('terminal_type');
    $changeTickets = array(); $change_f = false;
    $tc = Terminal_Check_Socket::connect();
    $chkIns = ($memberSID==1) ? '499':'260';
    if(strlen($voucher)==6)
    {// 凭证码
        if($terminal_type==1)
        {
            $chResult  = $tc->Terminal_Check_In_Voucher($terminal, $salerid, $voucher, array('vCmd'=>$chkIns));
            $ordernum  = $chResult["ordernum"];
            $checkData = json_encode(array($terminal, $salerid, $voucher, array('vCmd'=>$chkIns)));
            $logs = "[$ordernum]订单验证,操作人[$memberID],数据[$checkData],结果[".json_encode($chResult)."]";

            $ticket_count = count($chResult['tickets']);
            if($ticket_count>1 && isset($chResult['multi'])){//套票
                foreach($chResult['tickets'] as $row)
                {
                    $chResult_multi = $tc->Terminal_Check_In_Voucher($terminal, $salerid, $row['ticket_code'], array('vCmd'=>$chkIns));
                    $checkData = json_encode(array($terminal, $salerid, $row['ticket_code'], array('vCmd'=>$chkIns)));
                    $logs_multi = "[$ordernum]---订单验证,操作人[$memberID],数据[$checkData],结果[".json_encode($chResult_multi)."]";
                    PsVerfiy::logs($logs_multi, '/var/www/html/new/d/logs/terminal_check_pack.log');
                    if($chResult_multi['state']=='fail') exit('{"status":"fail","msg":"'.$chResult_multi['msg'].'"}');

                }
                if($chResult_multi['state']=='success')
                {
                    echo json_encode($verify->information($chResult_multi["ordernum"]));

                    exit();
                }
                exit('{"status":"fail","msg":"'.$chResult['msg'].'"}');
            }
            if($chResult['state']=='success')
            {
                echo json_encode($verify->information($ordernum));

                exit();
            }
            exit('{"status":"fail","msg":"'.$chResult['msg'].'"}');
        }
        else
        {
            //旧端口进行验证
            $simxml = $verify->check($voucher);

            if(is_numeric($simxml)) exit('{"status":"fail","msg":"'.$verify->errCode[$simxml].'"}');
            $simxml_o = simplexml_load_string($simxml);
            $ordernum = $simxml_o->Rec->UUordernum;// 已验证订单
            $uuino    =(string)$result->Rec->UUino;// 验证流水号
        }
        // 员工更新操作日志
        if($_SESSION['dtype']==6){
            $sql = "insert into pft_d_operation_rec set fid=$memberID,sid=$memberSID,daction='订单验证,订单号【".$ordernum."】',rectime=now()";
            $GLOBALS['le']->query($sql);
        }
        PsVerfiy::logs($logs, '/var/www/html/new/d/logs/terminal_check_new.log');
    }
    else if(strlen($voucher)==11 && is_numeric($voucher))
    {
        $mobile   = $voucher;
        $chResult = $tc->Terminal_Check_In_Mobile($terminal, $salerid, $mobile, array('vCmd'=>$chkIns));
        $ordernum = $chResult["ordernum"];
        $checkData = json_encode(array($terminal, $salerid, $mobile, array('vCmd'=>$chkIns)));
        $logs = "[$ordernum]订单验证,操作人[$memberID],数据[$checkData],结果[".json_encode($chResult)."]";
        // print_r($chResult);
        // exit;
        $ticket_count = count($chResult['tickets']);
        if($ticket_count>1 && isset($chResult['multi']))
        {
            echo json_encode($chResult);
            exit();
        }
        if($chResult['state']=='success')
        {
            echo json_encode($verify->information($chResult["ordernum"]));
            exit();
        }
        exit('{"status":"fail","msg":"'.$chResult['msg'].'"}');
    }
    else
    {
        exit('{"status":"fail","msg":"输入位数不正确或输入不正确"}');
    }
//	// 员工更新操作日志
//	if($_SESSION['dtype']==6){
//		$sql = "insert into pft_d_operation_rec set fid=$memberID,sid=$memberSID,daction='订单验证,订单号【".$ordernum."】',rectime=now()";
//		$GLOBALS['le']->query($sql);
//	}
//	// 记录日志
//	PsVerfiy::logs("[$ordernum]订单验证,操作人[$memberID]");
}
if(isset($_GET["code"])){
  /*
    $return = array (
        2012077 =>
            array (
                'ordernum' => '2012077',
                'ordername' => '1513132',
                'ordertel' => '18094156978',
                'ordertime' => '2015-08-21 10:23:49',
                'begintime' => '2015-08-21',
                'pmode' => '3',
                'status' => '1',
                'code' => '174695',
                'paystatus' => '1',
                'ptype' => 'F',
                'landid' => '10635',
                'tickets' =>
                    array (
                        0 =>
                            array (
                                'name' => '大床房',
                                'tnum' => 1,
                                'ordernum' => '2012079',
                                'tprice' => '1',
                            ),
                    ),
            ),
    );
    exit(json_encode($return));
    */
    // 接收数据
    $id       = $_REQUEST['id'] + 0;// 产品ID
    $terminal = $_REQUEST['terminal']+ 0;//终端号
    $salerid  = $_REQUEST['salerid'] + 0;// 产品编码
    $code     = $_GET["code"];
    $tc = Terminal_Check_Socket::connect();
    $verify   = new PsVerfiy($s, $salerid);
    $chkIns = ($memberSID==1) ? '499':'260';
    /*验证*/
    $chResult_multi = $tc->Terminal_Check_In_Voucher($terminal, $salerid, $code, array('vCmd'=>$chkIns));
    /*订单号*/
    $ordernum  = $chResult_multi["ordernum"];
    $checkData = json_encode(array($terminal, $salerid, $$code, array('vCmd'=>$chkIns)));

    $logs_multi = "[$ordernum]---订单验证,操作人[$memberID],数据[$checkData],结果[".json_encode($chResult_multi)."]";
    PsVerfiy::logs($logs_multi, '/var/www/html/new/d/logs/terminal_check_pack.log');
    if($chResult_multi['state']=='fail') exit('{"status":"fail","msg":"'.$chResult_multi['msg'].'"}');

    if($chResult_multi['state']=='success')
    {
        echo json_encode($verify->information($ordernum,"",true));
        exit();
    }
    exit('{"status":"fail","msg":"'.$chResult_multi['msg'].'"}');

}
if($salerid==0 || ($_REQUEST['voucher']+0)==0) exit('[]');

// 获取订单信息部分
$verify = new PsVerfiy($s, $salerid);
if(strlen($voucher)==6){// 凭证码
	$code     = $voucher;
	$ordernum = $verify->reverse($voucher);// 反查订单号
    $send     = array();
    /*注释 待删
    if(is_array($ordernum)){
        foreach ($ordernum as $v) {
            $send = array_merge($send,$verify->information($v));
        }
		if($_SESSION['account']=='124254'){
			 print_r($send);
			 exit;
		}

        echo json_encode($send);
        exit;
    }
    else
    */
        echo json_encode($verify->information($ordernum));
}elseif(strlen($voucher)==11 && is_numeric($voucher)){// 手机号

	$mobile = $voucher;
	$send = array();
	$status = ($_SESSION['sid']==1) ? '0|2':'0';// 0 未验证 2 已过期
	$xmlStr = $s->Order_Globle_Search($salerid,'','','','','','','','','','','','','',$mobile, $status,'','',1,0,0,100,'','','','','','','','','',0,0);
	$simxml = simplexml_load_string($xmlStr);
	$unique_a = array();// 多级转分校重复
	$unique_b = array();// 子票防止重复
	foreach($simxml->Rec as $row){

		if(isset($unique_a[(string)$row->UUordernum])) continue;
		$unique_a[(string)$row->UUordernum] = (string)$row->UUordernum;

		if((string)$row->UUpack_order!=0){
			if(isset($unique_b[(string)$row->UUpack_order])) continue;
			$unique_b[(string)$row->UUpack_order] = (string)$row->UUpack_order;
		}
		$send = array_merge($send, $verify->information((string)$row->UUordernum));

	}
	echo json_encode($send);

}else{// 身份证

	$idCard = $voucher;
	$simxml = $verify->checkIDCard('', $voucher);
	$simxml_o = simplexml_load_string($simxml);
	$send = array();
	$unique = array();// 子票防止重复
	foreach($simxml_o->Rec as $row){
		if((string)$row->UUpack_order!=0){
			if(isset($unique[(string)$row->UUpack_order])) continue;
			$unique[(string)$row->UUpack_order] = (string)$row->UUpack_order;
		}
		$send = array_merge($send, $verify->information((string)$row->UUordernum));
	}
	echo json_encode($send);

}
class PsVerfiy{

	public $inside = null;// 内部接口
	public $salerid = 0;  // 商户账号
	public $errCode = array(
		'105'=>'找不到订单',
		'121'=>'订单状态出错,订单已验证或已过期',
		'119'=>'订单状态出错,已取消或其他状态',
		'521'=>'验证间隔时间未到',
		'133'=>'游玩时间未到',
		'134'=>'游玩时间已过',
		'118'=>'终端服务器无响应',
		'1070'=>'订单未支付',
	);


	public function __construct($s, $salerid){
		$this->inside = $s;
		$this->salerid = $salerid;
	}

	// 验证
	public function check($voucher, $rtime='')
    {
		return $this->inside->Terminal_Check_In($this->salerid, $voucher, $rtime);
	}



	// 身份证获取所有订单信息
	public function checkIDCard($username, $idCard=null, $rtime=null){

		return $this->inside->Terminal_Check_IDcard($this->salerid, $username, $idCard, $rtime);
	}

	// 通过商户6位账号和凭证码反查订单
	public function reverse($voucher, $sid=0){

		$salerid = $this->salerid;
		if($sid==0) $sid = $_SESSION['sid'];
        //查重码
        /* 注释 待删
        $sql = "select id from uu_land where salerid=$salerid limit 1";
        $GLOBALS['le']->query($sql);
        $GLOBALS['le']->fetch_assoc();
        $lid = $GLOBALS['le']->f('id');
        $x = simplexml_load_string($this->inside->PFT_Order_Code( $sid,$voucher,-1,$lid));
        foreach ($x->Rec as $v) {
            $ordernum[] = (int)$v->UUordernum;
        }
        if(!count($ordernum))
        */
		    $ordernum = $this->inside->Code_Verify_Order($salerid, $voucher, $sid);
        return $ordernum;
	}

	// 获取订单信息
	public function information($orderId='', $mobile='',$flag=false){
		$init_order = $orderId;
		$sendData = array();
		$salerid = $this->salerid;
		$orderStatus = ($_SESSION['sid']==1) ? '0|2':'0';// 0 未验证 2 已过期
		if($orderId=='') return $sendData;
		$xmlStr = $this->inside->Order_Globle_Search($salerid,'','','','','','','','','','','',$orderId,'','', $orderStatus,'','',1,0,0,1,'','','','','','','','','',0,0);

		$simxml = simplexml_load_string($xmlStr);

		// 订单查找可能联票只能再次获取
		if($orderId!='' &&(string)$simxml->Rec->UUconcat_id==(string)$simxml->Rec->UUordernum){
			$xmlStr = $this->inside->Order_Globle_Search($salerid,'','','','','','','','','','','',$orderId,'',$mobile, $orderStatus,'','',1,0,0,100,'','','','','','','','','',1,0);
			$simxml = simplexml_load_string($xmlStr);
		}
		// 套票可能同一产品的两个不同子票会一起验证，所以都要显示出来
        if((string)$simxml->Rec->UUpack_order!=0 && $flag==false){
//            if((string)$simxml->Rec->UUstatus!=0) return $sendData;
            $orderId = (string)$simxml->Rec->UUpack_order;
            $xmlStr = $this->inside->Order_Globle_Search($salerid,'','','','','','','','','','','',$orderId,'',$mobile, $orderStatus,'','',1,0,0,100,'','','','','','','','','',0,2);
            $simxml = simplexml_load_string($xmlStr);

        }
		$sets_f = array();
		$same_f = 0;
		$isFirst = true;
		foreach($simxml->Rec as $order){

			if(in_array((string)$order->UUordernum, $sets_f)) continue;// 已经设置过，防止admin重复显示
			if((string)$order->UUpack_order!=0 && $flag==false){// 套票
				// 非第一次设置并且lid不跟第一样，并且不是这次查找的订单
				if($same_f!=0 //第一次执行
                    && (string)$order->UUlid!=$same_f
					&& (string)$order->UUordernum!=$init_order//
                )
//                    continue;// 不是统一产品底下的两个产品不显示
				if($order->UUstatus!=0) //continue;// 顺序问题
				$same_f = (string)$order->UUlid;
				// if((string)$order->UUp_type=='C'){// 酒店
					if($isFirst){
						$orderId = (string)$order->UUordernum;
						$isFirst = false;
					}
				// }else{
					// $orderId = (string)$order->UUordernum;
				// }
				// 第二次是要的的订单，说明之前的跟这次不一样，清空
				if(!$isFirst && (string)$order->UUordernum==$init_order){
					$sendData = array();
				}
			}
            elseif($order->UUconcat_id!=0 ){// 联票
				$concat = (string)$order->UUconcat_id;
				$ordernum = (string)$order->UUordernum;
				$orderId = ($concat==$ordernum) ? $ordernum:$concat;
				if($concat!=$ordernum && !isset($sendData[$orderId]['ordernum'])) continue;
			}else{

				$orderId = (string)$order->UUordernum;
			}

			if(!isset($sendData[$orderId]['ordernum'])){
				$sendData[$orderId]['ordernum'] = $orderId;//  订单号
				$sendData[$orderId]['ordername'] = (string)$order->UUordername;// 取票人姓名
				$sendData[$orderId]['ordertel'] = (string)$order->UUordertel;// 取票人手机
				$sendData[$orderId]['ordertime'] = (string)$order->UUordertime;// 下单时间
				$sendData[$orderId]['begintime'] = (string)$order->UUbegintime;// 游玩时间
				$sendData[$orderId]['pmode'] = (string)$order->UUpmode;
				$sendData[$orderId]['status'] = (string)$order->UUstatus;
				$sendData[$orderId]['code'] = (string)$order->UUcode;
				$sendData[$orderId]['paystatus'] = (string)$order->UUpaystatus;
				$sendData[$orderId]['ptype'] = (string)$order->UUp_type;
				$sendData[$orderId]['landid'] = (string)$order->UUlid;

				// 已过期的订单从 2015-06-30 开始不会显示已过期，订单显示 未使用 abc-2015-07-01
				if((int)$order->UUstatus==0){
					if((strtotime((string)$order->UUendtime)+86400)<time())
						$sendData[$orderId]['status'] = 2;
				}

				// 对于admin 过期产品返回使用开始时间
				if($_SESSION['sid']==1 && $sendData[$orderId]['status']){
					$sendData[$orderId]['endtime'] = (string)$order->UUendtime;
				}

				// 套票不允许改单验证
				if((string)$order->UUpack_order!=0){
					$sendData[$orderId]['ptype'] = 'F';
				}
			}
			$sendData[$orderId]['tickets'][] = array(
				'name'=>(string)$order->UUttitle,
				'tnum'=>(int)$order->UUtnum,
				'ordernum'=>(string)$order->UUordernum,
				'tprice'=>(string)$order->UUtprice
			);
			$sets_f[] = (string)$order->UUordernum;
		}
        return $sendData;
	}

	public static function logs($content, $file='/var/www/html/new/d/logs/terminal_check.log'){
		$fp = fopen($file,"a");
		flock($fp, LOCK_EX);
		fwrite($fp,date("Y-m-d H:i:s").":".$content."\n");
		flock($fp, LOCK_UN);
		fclose($fp);
	}
}

?>